
/**
 * This class implements a table that displays and allows the user to edit (but
 * not add) users for a server.
 *
 * @author Aaron A. Lovato
 */

import backend.*;
import javax.swing.table.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.JOptionPane;
import javax.swing.*;

public class UserViewTableModel extends AbstractTableModel 
implements TableModelListener
{
    private Server server;
    private String[] columns;
    private Object[][] data;
    
    
    public UserViewTableModel(Server server)
    {
        this.server = server;
        
        //Add the default values to the equation table
        columns = new String[2];
        columns[0] = "Username";
        columns[1] = "Password";
        
        // Populate data
        Collection<User> users = server.getUsers().values();
        data = new Object[users.size()][2];
        int row = 0;
        for(String user : server.getUsers().keySet())
        {
            data[row][0] = user;
            data[row][1] = server.getUsers().get(user).getPassword();
            row++;
        }
        
        addTableModelListener(this);
        
    }
    
    public int getColumnCount()
    {
        return columns.length;
    }
    
    public int getRowCount()
    {
        return data.length;
    }
    
    public String getColumnName(int col) 
    {
        return columns[col];
    }
    
    public Object getValueAt(int row, int col) 
    {
        return data[row][col];
    }
    
    public Class getColumnClass(int c) 
    {
        return getValueAt(0, c).getClass();
    }
    
    
    public void setValueAt(Object value, int row, int col) 
    {
        data[row][col] = value;
        fireTableCellUpdated(row, col);
    }
    
    public void tableChanged(TableModelEvent e)
    {
        if(e.getColumn() == 1)
        {
            // Update the changed permission
            String name = (String) data[e.getFirstRow()][0];
            String value = (String) data[e.getFirstRow()][1];
            if(name == null || name == "")
                return;
            try
            {
                server.setPassword(name, value);
            }
            catch(Exception error)
            {
                JOptionPane.showMessageDialog(null, error.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    public boolean isCellEditable(int row, int col) 
    {
        if(col == 1)
            return true;
        else
            return false;
    }
    
    public void rebuildTable()
    {
        // Something changed the underlying server so discard everything known      
        Collection<User> users = server.getUsers().values();
        data = new Object[users.size()][2];
        int row = 0;
        for(String user : server.getUsers().keySet())
        {
            data[row][0] = user;
            data[row][1] = server.getUsers().get(user).getPassword();
            row++;
        }

    }
}